<template>
    <div class="contract_detail_container">
        <el-tabs v-model="activeName" @tab-change="switchTab">
            <el-tab-pane v-for="item in tabList" :key="item.value" :label="item.label" :name="item.value"></el-tab-pane>
        </el-tabs>
        <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" />
        <ZwTable
            ref="tableRef"
            tab-h="initial"
            :option="tableOption"
            :fetch-params="state.searchParams"
            :param-prop="state.paramProp"
            :fetch-api="fetchApi()">
            <template #headerOperate>
                <el-button
                    v-auth="'ADVANCED_SET'"
                    plain
                    @click="router.push('/salesleads/salesmanagement/contractmanagement/advanceSet')"
                    >高级设置</el-button
                >
                <el-button
                    v-auth="'NEW_CONTRACT'"
                    type="primary"
                    @click="router.push('/salesleads/salesmanagement/contractmanagement/addContract')"
                    >新建合同</el-button
                >
            </template>
        </ZwTable>
        <ZWDeletdialog ref="submitRef" @submit="submit" />
        <Dialog :app-dialog="appDialog">
            <div class="dialog">
                <div v-if="isShow == 6 || isShow == 7">
                    <div>{{ isShow == 6 ? '您确定要通过该审批吗？' : '您确定要驳回该审批吗？请填写驳回原因：' }}</div>
                    <el-input
                        v-model="auditParams.remark"
                        class="remark"
                        :rows="3"
                        type="textarea"
                        placeholder="备注"></el-input>
                </div>
                <div v-if="isShow == 4" class="copy">
                    <div class="copy_title">您可以复制以下链接发送给客户签约：</div>
                    <div class="copy_content">{{ linkData }}</div>
                    <div class="copy_icon">
                        <el-icon @click="onCopy(linkData)"><CopyDocument /></el-icon>
                    </div>
                </div>
            </div>
        </Dialog>
    </div>
</template>

<script setup lang="tsx">
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import ZWDeletdialog from '@/components/ZWDeletdialog.vue';
import Dialog from '@/components/Dialog.vue';
import { ElButton, ElPopover } from 'element-plus';
import { ref, reactive, computed, onActivated, onMounted, onUnmounted, nextTick } from 'vue';
import { deepCopy } from '@/utils/helper';
import {
    contractList,
    submitContract,
    withdrawContract,
    signContract,
    auditContract,
    inviteContract,
    viewEc,
    generateEc,
    realName
} from '@/api/salesleads/contractmanagement/contract';
import { getDictEnum, downloadEC } from '@/api/ecommerce/storeManage';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import useClipboard from 'vue-clipboard3';
import { downFile } from '@/utils/utils';

const router = useRouter();
const { toClipboard } = useClipboard();
const activeName = ref('1');
const submitRef = ref(null);
const linkData = ref();
const tabList = reactive([
    { label: '全部合同', value: '1' },
    { label: '待审批合同', value: '2' }
]);
const auditParams = reactive({
    id: 0,
    audit_type: 1, //1-通过 2-驳回
    remark: ''
});

const isShow = ref(0);
const switchTab = () => {
    if (activeName.value == '2') {
        defaultParams.audit_state = '2';
    } else {
        defaultParams.audit_state = '-1';
    }
    reset();
};
const defaultParams = {
    type: activeName.value,
    title: '',
    contract_no: '',
    audit_state: '-1',
    cust_name: '',
    state: '-1',
    belong_staff_id: [],
    apply_time: [],
    pass_time: [],
    sign_time: []
};
const fetchApi = () => {
    getTableH();
    return contractList;
};
const tableRef = ref<any>(null);
const state = reactive({
    searchParams: deepCopy(defaultParams),
    paramProp: { page: '', pageSize: 'page_size' }
});
const cancelHandel = () => {
    appDialog.visible = false;
};
const submitHandel = () => {
    isShow.value == 6 ? (auditParams.audit_type = 1) : (auditParams.audit_type = 2);
    auditContract(auditParams).then((res: any) => {
        ElMessage.success('审批成功');
        appDialog.visible = false;
        tableRef.value.reload();
    });
};
const getTableH = () => {
    nextTick(() => {
        tableRef.value.getTableH();
    });
};
onMounted(() => {
    getTableH();
});
const appDialog: any = reactive({
    visible: false,
    title: '通过审批提醒',
    width: '500px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '确定'
});
const searchOption = computed(() => {
    return [
        {
            label: '合同名称',
            name: 'title',
            value: '',
            type: 'input',
            placeholder: '请输入合同名称'
        },
        {
            label: '合同编号',
            name: 'contract_no',
            value: '',
            type: 'input',
            placeholder: '请输入合同编号'
        },
        {
            label: '所属员工',
            name: 'belong_staff_id',
            value: [],
            type: 'select',
            placeholder: '请选择所属员工',
            multiple: true,
            popperClass: 'zw-hide_select_option',
            isUserSelect: true,
            filterable: true,
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '审批状态',
            name: 'audit_state',
            value: '',
            type: 'select',
            disabled: activeName.value == '2',
            placeholder: activeName.value == '2' ? '审批中' : '请选择审批状态',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    const params = { dict_id: 9 };
                    getDictEnum(params).then((res: any) => {
                        const targetArr: any = [];
                        res.forEach((item: any) => {
                            targetArr.push(item);
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '客户名称',
            name: 'cust_name',
            value: '',
            type: 'input',
            placeholder: '请输入客户名称'
        },
        {
            label: '合同状态',
            name: 'state',
            value: '',
            type: 'select',
            placeholder: '请选择签署状态',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    const params = { dict_id: 10 };
                    getDictEnum(params).then((res: any) => {
                        const targetArr: any = [];
                        res.forEach((item: any) => {
                            targetArr.push(item);
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '提交时间',
            name: 'apply_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'datetimerange',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        },
        {
            label: '通过时间',
            name: 'pass_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'datetimerange',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        },
        {
            label: '签约时间',
            name: 'sign_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'datetimerange',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        }
    ];
});
const search = (v: any) => {
    state.searchParams = { ...deepCopy(defaultParams), ...v, type: activeName.value };
};
const reset = (v?: any) => {
    state.searchParams = { ...deepCopy(defaultParams), type: activeName.value };
};
//按钮操作
const contractBtn = async (val: any, id: any) => {
    switch (id) {
        case 0: // 详情
            router.push('/salesleads/salesmanagement/contractmanagement/contractDetail?id=' + val.id);
            break;
        case 1: //提交审批
            submitRef.value.appDialog.title = '提交审批提醒';
            submitRef.value.content = '您确定要提交审批吗？';
            submitRef.value.appDialog.visible = true;
            break;
        case 2: // 编辑
            router.push(
                `/salesleads/salesmanagement/contractmanagement/addContract?id=${val.id}&pageType=edit&type=edit`
            );
            break;
        case 3: //撤回
            submitRef.value.appDialog.title = '撤回审批提醒';
            submitRef.value.content = '您确定要撤回该审批吗？';
            submitRef.value.appDialog.visible = true;
            break;
        case 4: //签约邀请
            getInvite(val.id);
            break;
        case 5: //签署合同
            submitRef.value.appDialog.title = '签署合同提醒';
            submitRef.value.content = '您确定要签署该合同吗？';
            submitRef.value.appDialog.visible = true;
            break;
        case 6: // 通过
            appDialog.title = '通过审批提醒';
            auditParams.remark = '';
            appDialog.visible = true;
            break;
        case 7: // 驳回
            appDialog.title = '驳回审批提醒';
            auditParams.remark = '';
            appDialog.visible = true;
            break;
        case 8: //生成电子合同
            getgenerateEc(val.id);
            break;
        case 9: //客户实名认证
            getRealName(val.id);
            break;
        case 10: //查看
            getViewEc(val.id);
            break;
        case 11: //下载合同
            await downloadFn(val.id);
            break;
    }
    isShow.value = id;
    auditParams.id = val.id;
};

const downloadFn = async (id: any) => {
    const { contract_url } = await downloadEC({ id });
    if (contract_url) {
        downFile(contract_url, '');
    }
};

const getViewEc = (val: any) => {
    viewEc({ id: val }).then((res: any) => {
        window.open(res.viewpdf_url);
    });
};
const getRealName = (val: any) => {
    realName({ id: val }).then((res: any) => {
        ElMessage.success('客户实名认证成功');
        tableRef.value.reload();
    });
};
const getgenerateEc = (val: any) => {
    generateEc({ id: val }).then((res: any) => {
        ElMessage.success('生成电子合同成功');
        tableRef.value.reload();
    });
};
const getInvite = async (val: any) => {
    const res = await inviteContract({ id: val });
    linkData.value = res.link_url;
    appDialog.title = '签约邀请';
    appDialog.isHiddenFoot = true;
    appDialog.visible = true;
};
const onCopy = async (v: any) => {
    try {
        await toClipboard(v);
        ElMessage.success('复制成功');
    } catch (e) {
        ElMessage.error('复制失败');
    }
};
const submit = async () => {
    const params = auditParams.id;
    switch (isShow.value) {
        case 1:
            await submitContract({ id: params });
            ElMessage.success('提交审批成功');
            submitRef.value.appDialog.visible = false;
            tableRef.value.reload();
            break;
        case 3:
            await withdrawContract({ id: params });
            ElMessage.success('撤回审批成功');
            submitRef.value.appDialog.visible = false;
            tableRef.value.reload();
            break;
        case 5:
            await signContract({ id: params });
            ElMessage.success('签署合同成功');
            submitRef.value.appDialog.visible = false;
            tableRef.value.reload();
            break;
    }
};
const sopBtnList = reactive([
    { id: 0, val: '详情', authCode: 'CONTRACT_DETAIL' },
    { id: 1, val: '提交审批', authCode: 'SUBMIT_APPROVAL' },
    { id: 2, val: '编辑', authCode: 'EDIT_CONTRACT' },
    { id: 3, val: '撤回', authCode: 'WIDTHDRAW' },
    { id: 4, val: '签约邀请', authCode: 'SINGIN_INVIT' },
    { id: 5, val: '签署合同', authCode: 'SIGN_CONTRACT' },
    { id: 6, val: '通过', authCode: 'ADOPT' },
    { id: 7, val: '驳回', authCode: 'REJECT' },
    { id: 8, val: '生成电子合同', authCode: 'GENER_CONTRACT' },
    { id: 9, val: '客户实名认证', authCode: 'REAL_NAME' },
    { id: 10, val: '查看', authCode: 'VIEW_CONTRACT' },
    { id: 11, val: '下载合同', authCode: 'DOWNLOAD_CONTRACT' }
]);
const executor = {
    color: '#000000',
    ['font-size']: '12px'
};
// 表格
const tableOption = computed(() => {
    const arr = [
        {
            prop: 'contract_no',
            label: '合同编号',
            width: 200
        },
        {
            prop: 'title',
            label: '合同名称',
            width: 200,
            showOverflowTooltip: true
        },
        {
            prop: 'cust_name',
            label: '合同客户',
            minWidth: 240,
            render({ row, column, index }: any) {
                return row.cust_name ?? '--';
            }
        },
        {
            prop: 'contract_amount',
            label: '合同金额',
            width: 140
        },
        {
            prop: 'audit_state',
            label: '审批状态',
            width: 140,
            render({ row, column, index }: any) {
                return row.audit_state == 1
                    ? '待提交'
                    : row.audit_state == 2
                    ? '审批中'
                    : row.audit_state == 3
                    ? '已撤回'
                    : row.audit_state == 4
                    ? '已驳回'
                    : '已通过';
            }
        },
        {
            prop: 'state',
            label: '合同状态',
            width: 200,
            render({ row, column, index }: any) {
                if (row.is_expire == 2) {
                    return '已过期';
                } else {
                    if (row.first_state == 1 && row.second_state == 1) {
                        return '未签约';
                    } else if (row.first_state == 1 && row.second_state == 2) {
                        return '乙方已签约';
                    } else if (row.first_state == 2 && row.second_state == 1) {
                        return '甲方已签约';
                    } else if (row.first_state == 2 && row.second_state == 2) {
                        return '双方已签约（已生效）';
                    }
                }
            }
        },
        {
            prop: 'apply_time',
            label: '提交审批时间',
            render({ row, column, index }: any) {
                return row.apply_time ?? '--';
            }
        },
        {
            prop: 'audit_work_user_name',
            label: '当前审批人',
            render({ row, column, index }: any) {
                const slotReference = () => (
                    <span>{`${row.audit_work_user_name[0].name}、${row.audit_work_user_name[1].name}、${row.audit_work_user_name[2].name}等${row.audit_work_user_name.length}人`}</span>
                );
                const slotDefault = () => (
                    <div>
                        {row.audit_work_user_name.map((item: any, index: any) => {
                            return (
                                <span style={executor}>
                                    {item.name}
                                    <span v-show={row.audit_work_user_name.length - 1 !== index}>、</span>
                                </span>
                            );
                        })}
                    </div>
                );
                if (row.audit_work_user_name?.length > 3) {
                    return (
                        <div>
                            <ElPopover
                                popper-class="popGroup"
                                trigger="hover"
                                vSlots={{ reference: slotReference, default: slotDefault }}
                                width={300}
                                popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 20px;"></ElPopover>
                        </div>
                    );
                } else {
                    return (
                        <div>
                            {row.audit_work_user_name?.map((item: any, index: any) => {
                                return (
                                    <span>
                                        {item.name}
                                        <span v-show={row.audit_work_user_name?.length - 1 !== index}>、</span>
                                    </span>
                                );
                            })}
                        </div>
                    );
                }
            }
        },
        {
            prop: 'staff_name',
            label: '所属员工',
            width: 140,
            render({ row, column, index }: any) {
                return row.staff_name ?? '--';
            }
        },
        {
            prop: 'operate',
            label: '操作',
            width: 300,
            fixed: 'right',
            isOperate: true,
            renderOperate({ row, column, index }) {
                return sopBtnList.map((item: any, index: number) => {
                    return (
                        <span v-show={row.button.includes(item.id) || item.id == 0}>
                            <ElButton size="small" v-auth={item.authCode} onClick={() => contractBtn(row, item.id)}>
                                {item.val}
                            </ElButton>
                        </span>
                    );
                });
            }
        }
    ];
    if (activeName.value == '1') {
        arr.splice(6, 2);
    } else {
        arr.splice(5, 1);
    }
    return arr;
});
</script>
<style lang="scss" scoped>
.contract_detail_container {
    height: calc(100vh - 142px);
    padding: 24px;
    padding-top: 10px;
    border: 1px solid #eaeaea;
    border-radius: 4px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .zw-table {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: hidden;

        :deep(.el-table) {
            flex: 1;

            .el-table__empty-block {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
    }
}

.dialog {
    padding: 15px 10px;

    .remark {
        margin-top: 15px;
    }

    .copy {
        .copy_title {
            font-size: 14px;
            font-weight: 500;
            line-height: 1;
            margin-bottom: 10px;
        }

        .copy_content {
            margin-bottom: 10px;
            font-size: 12px;
            color: #999;
            line-height: 1.6;
            word-break: break-all;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            overflow: hidden;
        }

        .copy_icon {
            .el-icon {
                cursor: pointer;
                color: #ff6b00;
                width: 14px;
                height: 14px;
            }
        }
    }
}
</style>
